import json
import random

import time

import datetime
from django import http
from django.core.paginator import Paginator
from django.views import View

from home.models import Area, House, HouseImage
from order.models import Order
from tenement_project.libs.qiniuyun.qiniu_storage import storage
from tenement_project.utils import constants
from tenement_project.utils.fastdfs.new_upavatar import up_house_image, qiliuyun_house_image
from tenement_project.utils.response_code import RET


# 地区
class AreasView(View):
    def get(self, request):
        area_list = Area.objects.all()
        data_list = []
        for area in area_list:
            data_dict = {
                "aid": area.id,
                "aname": area.name
            }
            data_list.append(data_dict)
        context = {"errno": RET.OK,
                   "errmsg": "已验证",
                   "data": data_list
                   }
        return http.JsonResponse(context)


# 发布新房源
class NewHouseView(View):
    def post(self, request):
        user = request.user
        if user.is_authenticated:
            data_dict = json.loads(request.body.decode())
            title = data_dict["title"]
            price = data_dict["price"]
            area_id = data_dict["area_id"]
            address = data_dict["address"]
            room_count = data_dict["room_count"]
            acreage = data_dict["acreage"]
            unit = data_dict["unit"]
            capacity = data_dict["capacity"]
            beds = data_dict["beds"]
            deposit = data_dict["deposit"]
            min_days = data_dict["min_days"]
            max_days = data_dict["max_days"]
            # 弹出设施的内容
            facility_list = data_dict.pop("facility")
            # 加入user_id 否则无法创建房子对象
            data_dict["user_id"] = user.id
            if not user.avatar:
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "未伤春"})

            if not all([title, price, area_id, address, room_count, acreage, unit, capacity,
                        beds, deposit, min_days, max_days]):
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "房源信息不完整"})
            # 不校验了 太多
            new_house = House.objects.create(**data_dict)
            #
            # 遍历设施id  添加入多对多的表
            for facility in facility_list:
                new_house.facility.add(facility)

            new_house.save()

            return http.JsonResponse({"errno": RET.OK, "data": {"house_id": new_house.id}})

        else:
            context = {
                "errno": RET.SESSIONERR,
                "errmsg": "未登录"
            }
            return http.JsonResponse(context)

    def get(self, request):
        aid = request.GET.get("aid")
        sd = request.GET.get("sd")
        ed = request.GET.get("ed")

        sk = request.GET.get("sk")
        p = request.GET.get("p")
        if not all([aid, sd, ed, p, sk]):
            return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "入住日期有误"})

        try:
            area = Area.objects.get(id=aid)
        except Exception as e:
            return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "房源区域有误"})
        sd = datetime.datetime.strptime(sd, '%Y-%m-%d').date()
        ed = datetime.datetime.strptime(ed, '%Y-%m-%d').date()
        # 根据sort 设置数据中查询的排序字段
        if sk == "booking":
            sort_filed = "order_count"  # 按照价格降序排序
        elif sk == "price-inc":
            sort_filed = "price"  # 按照销量升序排序
        elif sk == "price-des":
            sort_filed = "price"  # 按照销量降序排序
        else:
            sort_filed = "create_time"  # 按照创建时间升序排序
        area_house = area.house_set.all().order_by(sort_filed)  # 区域内所有房子
        house_list = []
        for one_house in area_house:  # 遍历区域内的每一个房子
            house_orders = one_house.order_set.all()
            if house_orders:
                for time in house_orders:  # 判断是否有人预定 这段想了挺久
                    if time.begin_date <= sd <= time.end_date or time.begin_date <= ed <= time.end_date:
                        continue
                    if time.status in [0, 1, 2]:
                        continue
                    house_dict = {
                        "address": one_house.address,
                        "area_name": area.name,
                        "ctime": one_house.create_time.strftime("%Y-%m-%d"),
                        "house_id": one_house.id,
                        "img_url": one_house.index_image_url,
                        "order_count": one_house.order_count,
                        "price": one_house.price,
                        "room_count": one_house.room_count,
                        "title": one_house.title,
                        "user_avatar": one_house.user.avatar.url
                    }
                    house_list.append(house_dict)
            else:
                house_dict = {
                    "address": one_house.address,
                    "area_name": area.name,
                    "ctime": one_house.create_time.strftime("%Y-%m-%d"),
                    "house_id": one_house.id,
                    "img_url": one_house.index_image_url,
                    "order_count": one_house.order_count,
                    "price": one_house.price,
                    "room_count": one_house.room_count,
                    "title": one_house.title,
                    "user_avatar": one_house.user.avatar.url
                }
                house_list.append(house_dict)

        paginator = Paginator(house_list, 3)
        paginate = paginator.page(p)
        new_house_list = paginate.object_list  # 当前页对象列表
        # current_page = paginate.number  # 当前页
        total_page = paginator.num_pages  # 总页数

        context = {
            "data": {
                "houses": new_house_list,
                "total_page": total_page
            },
            "errmsg": "请求成功",
            "errno": RET.OK
        }
        return http.JsonResponse(context)


# 上传新房源图片
class NewHouseImageView(View):
    def post(self, request, house_id):
        user = request.user
        if user.is_authenticated:
            # 上传图片
            house_image = request.FILES
            house_image_data = house_image["house_image"]
            # up_house_image(house_image_data.read(), house_id)  # 自定义上传本地图片方法
            url = qiliuyun_house_image(house_image_data, house_id)
            # house = House.objects.get(id=house_id)
            context = {
                "errno": RET.OK,
                "errmsg": "图片上传成功",
                "data": {"url": url}
            }
            return http.JsonResponse(context)
        else:
            context = {
                "errno": RET.SESSIONERR,
                "errmsg": "未登录"
            }
            return http.JsonResponse(context)


# 用户房源中心
class UserHouseView(View):
    def get(self, request):
        # 获取该用户所有房子的信息
        user_houses = House.objects.filter(user=request.user.id).order_by("-create_time")
        # 拼接数据
        houses_list = [{
            "address": house.address,
            "area_name": house.area.name,
            "ctime": house.create_time.strftime("%Y-%m-%d"),  # %H:%M:%S"
            "house_id": house.id,
            "img_url": house.index_image_url,
            "order_count": house.order_count,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "user_avatar": house.user.avatar.url
        } for house in user_houses]

        context = {
            "errno": RET.OK,
            "data": {"houses": houses_list}
        }
        return http.JsonResponse(context)


# 主页房源图片
class IndexImageView(View):
    def get(self, request):
        # 取出所有房子的id
        all_house = House.objects.all().values_list('id', flat=True)
        # 随机取出对象列表里面五个房源德图片
        all_house_list = list(all_house)
        try:
            if 0 < len(all_house_list) < 5:
                random_house = random.sample(all_house_list, len(all_house_list))
            else:
                random_house = random.sample(all_house_list, constants.INDEX_IMAGE_EXPIRES)

        except Exception as e:
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "目前没有房源！"})
        else:
            index_house_list = []
            for house in random_house:
                index_house = House.objects.get(id=house)
                data_dict = {
                    "house_id": house,
                    "img_url": index_house.index_image_url,
                    "title": index_house.title
                }
                index_house_list.append(data_dict)
            context = {
                "errno": RET.OK,
                "data": index_house_list
            }

            return http.JsonResponse(context)


# 房子详情页
class DetailView(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return http.HttpResponseForbidden("此房源已失效")
        all_order = house.order_set.all()
        # 所有评价数据
        comments_list = [{
            "comment": order.comment,
            "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),  # %H:%M:%S,
            "user_name": order.user.username
        } for order in all_order if order.status == 4]  # 当订单状态显示已完成时候才显示
        # 所有设施数据
        all_facility = house.facility.all()
        facility_list = [facility.id for facility in all_facility]
        # 所有图片链接
        all_image_obj = house.houseimage_set.all()
        all_urls_list = [image.url for image in all_image_obj]
        all_urls_list.insert(0, house.index_image_url)
        # 登录用户id
        if request.user.is_authenticated:
            user_id = request.user.id
        else:
            user_id = -1

        context = {
            "data": {
                "house": {
                    "acreage": house.acreage,
                    "address": house.address,
                    "beds": house.beds,
                    "capacity": house.capacity,
                    "comments": comments_list,
                    "deposit": house.deposit,
                    "facilities": facility_list,
                    "hid": house.id,
                    "img_urls": all_urls_list,
                    "max_days": house.max_days,
                    "min_days": house.min_days,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "unit": house.unit,
                    "user_avatar": house.user.avatar.url,
                    "user_id": house.user_id,
                    "user_name": house.user.username
                },
                "user_id": user_id
            },
            "errmsg": "获取房子信息成功",
            "errno": RET.OK
        }
        return http.JsonResponse(context)
